import { log } from "@/utils/common/log_util";

type PageCallback = (res : any) => void

const navigateBack = (delta ?: number) : void => {
	uni.navigateBack({ delta: delta })
}

//页面跳转Entity
interface PageOptions {
	url : string; //路由名称
	params ?: Record<string, any>; //路由入参
	success ?: (result : any) => void;
	isRedirect ?: boolean; //跳转下个页面时，是否关闭当前页面
}

//返回页面Url
const _getPageUrl = (url : string, params ?: any) : string => {
	//页面传值入参
	const queryString = params
		? Object.keys(params)
			.map((key) => `${key}=${params[key]}`)
			.join('&')
		: ''
	log('跳转路由', `/pages/${url}?${queryString}`)
	return `/pages/${url}?${queryString}`;
};

//页面跳转
function _navigateTo(options : PageOptions) : void {
	uni.navigateTo({
		url: _getPageUrl(options.url, options.params),
		success: (result) => {
			if (options.success) {
				options.success(result)
			}
		},
		fail: (err) => {
			log(JSON.stringify(err))
		}
	});
}

//页面跳转并关闭当前
function _redirectTo(options : PageOptions) : void {
	uni.redirectTo({
		url: _getPageUrl(options.url, options.params),
		success: (result) => {
			if (options.success) {
				options.success(result)
			}
		}
	});
}

//页面跳转
function pageTo(options : PageOptions) : void {
	if (options.isRedirect) {
		_redirectTo(options);
	} else {
		_navigateTo(options);
	}
}

//页面跳转，并关闭前面所有页面
function reLaunch(options : PageOptions) : void {
	uni.reLaunch({
		url: _getPageUrl(options.url)
	});
}

//页面跳转，Tab页
function switchTab(options : PageOptions) : void {
	uni.switchTab({
		url: _getPageUrl(options.url)
	});
}

export {
	navigateBack,
	pageTo,
	reLaunch,
	switchTab,
	PageCallback,
}